<?php

namespace app\index\controller;
class Login
{
    protected $code = "";
    protected $uniacid;
    protected $request;
    protected $_param;
    protected $_input;

    public function __construct(\think\App $app)
    {
        global $_GPC;
        global $_W;
        $this->request = $app->request;
        $this->_param = $this->request->param();
        $this->_input = json_decode($this->request->getInput(), true);
        if (!isset($this->_param["i"]) || !$this->_param["i"]) {
            return $this->error("need uniacid", 400);
        }
        $this->uniacid = $this->_param["i"];
    }

    public function error($msg, $code = 400, $msg_code = 400)
    {
        $result["error"] = $msg;
        $result["code"] = $msg_code;
        return $this->response($result, "json", $code);
    }

    protected function response($data, $type = "json", $code = 200)
    {
        return \think\Response::create($data, $type)->code($code);
    }

    public function index()
    {
        $input = $this->_input;
        if (!isset($input["code"]) || !$input["code"]) {
            return $this->error(["code" => 400, "error" => "need code"]);
        }
        $cap_id = !empty($input["cap_id"]) ? $input["cap_id"] : 0;
        $code = $input["code"];
        $config = longbingGetAppConfig($this->uniacid, true);
        if (!empty($input["is_coach"])) {
            $appid = getConfigSetting($this->uniacid, "coach_appid");
            $appsecret = getConfigSetting($this->uniacid, "coach_appsecret");
        } else {
            $appid = $config["appid"];
            $appsecret = $config["appsecret"];
        }
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $appsecret . "&js_code=" . $code . "&grant_type=authorization_code";
        $arrContextOptions = ["ssl" => ["verify_peer" => false, "verify_peer_name" => false]];
        $info = file_get_contents($url, false, stream_context_create($arrContextOptions));
        $info = @json_decode($info, true);
        if (isset($info["errcode"])) {
            return $this->error($info["errcode"] . ", errmsg: " . $info["errmsg"]);
        }
        if (!isset($info["session_key"])) {
            return $this->error("session_key not exists", "402");
        }
        if (empty($info["openid"])) {
            return $this->error("openid not exists");
        }
        $user_model = new \app\massage\model\User();
        $unionid = !empty($info["unionid"]) ? $info["unionid"] : "";
        if (empty($unionid)) {
            return $this->error("请将小程序绑定到开发平台");
        }
        if (!empty($unionid)) {
            $dis = ["unionid" => $unionid, "uniacid" => $this->uniacid, "status" => 1];
        } else {
            $dis = ["openid" => $info["openid"], "uniacid" => $this->uniacid, "status" => 1];
        }
        $user_info = $user_model->dataInfo($dis);
        if (empty($user_info)) {
            $dis = ["wechat_openid" => $info["openid"], "status" => 1];
            $user_info = $user_model->dataInfo($dis);
        }
        $insert = ["uniacid" => $this->uniacid, "openid" => $info["openid"], "wechat_openid" => $info["openid"], "cap_id" => $cap_id, "session_key" => $info["session_key"], "unionid" => $unionid, "last_login_type" => 0];
        if (empty($user_info)) {
            $insert = $user_model->getRegisterLocation($input, $insert, $this->uniacid);
            $bind_model = new \app\massage\model\QrBind();
            if (!empty($input["pid"])) {
                $insert["pid"] = $input["pid"];
            } else {
                $insert["pid"] = $bind_model->getPid($insert["openid"], $insert["unionid"]);
            }
            if (!empty($insert["pid"]) && getFxStatus($this->uniacid) == 1) {
                $distribu_model = new \app\massage\model\DistributionList();
                $dis = ["user_id" => $insert["pid"], "status" => 2];
                $distribu_user = $distribu_model->dataInfo($dis);
                if (!empty($distribu_user)) {
                    $insert["admin_id"] = $distribu_user["admin_id"];
                } else {
                    $insert["pid"] = 0;
                }
            }
            $user_model->dataAdd($insert);
            $user_id = $user_model->getLastInsID();
            $user_info = $user_model->dataInfo($insert);
            $qr_model = new \app\massage\model\ChannelQr();
            $qr_model->locationLogin($user_id);
            if (!empty($distribu_user)) {
                $insert["id"] = $user_id;
                $reseller_recommend_model = new \app\massage\model\ResellerRecommendCash();
                $reseller_recommend_model->addRecommendCash($insert, $distribu_user);
            }
            $register = 1;
        } else {
            $register = 0;
            $user_model->dataUpdate(["id" => $user_info["id"]], $insert);
        }
        $key = "longbing_user_autograph_wechat" . $user_info["openid"];
        $key = md5($key);
        setCache($key, $user_info, 259200, 0);
        $arr = ["data" => $user_info, "autograph" => $key, "is_register" => $register];
        $coach_model = new \app\massage\model\Coach();
        $cap_dis[] = ["user_id", "=", $user_info["id"]];
        $cap_dis[] = ["status", "in", [1, 2, 3, 4]];
        $cap_info = $coach_model->where($cap_dis)->order("status")->find();
        $cap_info = !empty($cap_info) ? $cap_info->toArray() : [];
        $arr["coach_status"] = !empty($cap_info) ? $cap_info["status"] : -1;
        return $this->success($arr);
    }

    public function success($data, $code = 200)
    {
        $result["data"] = $data;
        $result["code"] = $code;
        $result["sign"] = NULL;
        return $this->response($result, "json", $code);
    }

    public function appLogin()
    {
        $input = $this->_input;
        $uniacid = $this->uniacid;
        $input = $input["data"];
        $cap_id = !empty($input["cap_id"]) ? $input["cap_id"] : 0;
        $user_model = new \app\massage\model\User();
        $dis = ["unionid" => $input["unionId"], "status" => 1];
        $user_info = $user_model->dataInfo($dis);
        if (empty($user_info) && !empty($input["openId"])) {
            $dis = ["app_openid" => $input["openId"], "status" => 1];
            $user_info = $user_model->dataInfo($dis);
        }
        $insert = ["uniacid" => $uniacid, "nickName" => !empty($user_info["nickName"]) ? $user_info["nickName"] : $input["nickName"], "avatarUrl" => !empty($user_info["avatarUrl"]) ? $user_info["avatarUrl"] : $input["avatarUrl"], "unionid" => $input["unionId"], "gender" => $input["gender"], "city" => $input["city"], "province" => $input["province"], "country" => $input["country"], "openid" => $input["openId"], "app_openid" => $input["openId"], "cap_id" => $cap_id, "last_login_type" => 1];
        if (empty($user_info)) {
            $insert = $user_model->getRegisterLocation($input, $insert, $this->uniacid);
            $bind_model = new \app\massage\model\QrBind();
            if (!empty($input["pid"])) {
                $insert["pid"] = $input["pid"];
            } else {
                $insert["pid"] = $bind_model->getPid($insert["openid"], $insert["unionid"]);
            }
            if (!empty($insert["pid"]) && getFxStatus($this->uniacid) == 1) {
                $distribu_model = new \app\massage\model\DistributionList();
                $dis = ["user_id" => $insert["pid"], "status" => 2];
                $distribu_user = $distribu_model->dataInfo($dis);
                if (!empty($distribu_user)) {
                    $insert["admin_id"] = $distribu_user["admin_id"];
                } else {
                    $insert["pid"] = 0;
                }
            }
            $user_model->dataAdd($insert);
            $user_id = $user_model->getLastInsID();
            $qr_model = new \app\massage\model\ChannelQr();
            $qr_model->locationLogin($user_id);
            if (!empty($distribu_user)) {
                $insert["id"] = $user_id;
                $reseller_recommend_model = new \app\massage\model\ResellerRecommendCash();
                $reseller_recommend_model->addRecommendCash($insert, $distribu_user);
            }
        } else {
            $user_id = $user_info["id"];
            $user_model->dataUpdate(["id" => $user_id], $insert);
        }
        $user_info = $user_model->dataInfo(["id" => $user_id]);
        $key = "longbing_user_autograph_app" . $user_info["unionid"];
        $key = md5($key);
        setCache($key, $user_info, 259200, 0);
        $arr = ["data" => $user_info, "autograph" => $key];
        $coach_model = new \app\massage\model\Coach();
        $cap_dis[] = ["user_id", "=", $user_info["id"]];
        $cap_dis[] = ["status", "in", [1, 2, 3, 4]];
        $cap_info = $coach_model->where($cap_dis)->order("status")->find();
        $cap_info = !empty($cap_info) ? $cap_info->toArray() : [];
        $arr["coach_status"] = !empty($cap_info) ? $cap_info["status"] : -1;
        return $this->success($arr);
    }

    public function getCode($appId)
    {
        $url = "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"] . "?" . $_SERVER["QUERY_STRING"];
        $url = str_replace("&state=STATE", "", $url);
        $url = str_replace("&from=singlemessage", "", $url);
        $url2 = urlencode($url);
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $appId . "&redirect_uri=" . $url2 . "&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect";
        header("Location:" . $url);
        exit;
    }

    public function test()
    {
        dump($_GET);
        exit;
    }

    public function test1()
    {
        $model = new \app\massage\model\SendMsgConfig();
        $a = $model->unpaidOrdersNotice(666);
        dump($a);
    }

    public function webLogin()
    {
        $input = $this->_input;
        $config = longbingGetAppConfig($this->uniacid, true);
        $appid = $config["web_app_id"];
        if (!isset($input["code"]) || !$input["code"]) {
            return $this->error("need code");
        }
        $uniacid = $this->_param["i"];
        $cap_id = !empty($input["cap_id"]) ? $input["cap_id"] : 0;
        $code = $input["code"];
        $appsecret = $config["web_app_secret"];
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $appsecret . "&code=" . $code . "&grant_type=authorization_code";
        $info = file_get_contents($url);
        $info = @json_decode($info, true);
        if (isset($info["errcode"])) {
            return $this->error($info["errcode"] . ", errmsg: " . $info["errmsg"], 40163);
        }
        $token = $info["access_token"];
        $openid = $info["openid"];
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $token . "&openid=" . $openid;
        $json = file_get_contents($url);
        $arr = json_decode($json, true);
        if (isset($arr["errcode"])) {
            return $this->error($arr["errcode"] . ", errmsg: " . $arr["errmsg"], 40163);
        }
        if (empty($info["openid"])) {
            return $this->error("openid not exists");
        }
        $user_model = new \app\massage\model\User();
        $unionid = !empty($info["unionid"]) ? $info["unionid"] : "";
        if (empty($unionid)) {
        }
        if (!empty($unionid)) {
            $dis = ["unionid" => $unionid, "uniacid" => $this->uniacid, "status" => 1];
        } else {
            $dis = ["openid" => $info["openid"], "uniacid" => $this->uniacid, "status" => 1];
        }
        $user_info = $user_model->dataInfo($dis);
        if (empty($user_info)) {
            $dis = ["web_openid" => $info["openid"], "status" => 1];
            $user_info = $user_model->dataInfo($dis);
        }
        $insert = ["uniacid" => $uniacid, "nickName" => !empty($user_info["nickName"]) ? $user_info["nickName"] : $arr["nickname"], "avatarUrl" => !empty($user_info["avatarUrl"]) ? $user_info["avatarUrl"] : $arr["headimgurl"], "unionid" => $unionid, "gender" => $arr["sex"], "country" => $arr["country"], "openid" => $arr["openid"], "web_openid" => $arr["openid"], "cap_id" => $cap_id, "last_login_type" => 2, "ip" => getIP()];
        if (empty($user_info)) {
            $insert = $user_model->getRegisterLocation($input, $insert, $this->uniacid);
            $bind_model = new \app\massage\model\QrBind();
            if (!empty($input["pid"])) {
                $insert["pid"] = $input["pid"];
            } else {
                $insert["pid"] = $bind_model->getPid($insert["openid"], $insert["unionid"]);
            }
            if (!empty($insert["pid"]) && getFxStatus($this->uniacid) == 1) {
                $distribu_model = new \app\massage\model\DistributionList();
                $dis = ["user_id" => $insert["pid"], "status" => 2];
                $distribu_user = $distribu_model->dataInfo($dis);
                if (!empty($distribu_user)) {
                    $insert["admin_id"] = $distribu_user["admin_id"];
                } else {
                    $insert["pid"] = 0;
                }
            }
            $scan_model = new \app\massage\model\ChannelScanQr();
            $insert = $scan_model->getQrRegister($insert["web_openid"], $insert);
            $user_model->dataAdd($insert);
            $user_id = $user_model->getLastInsID();
            if (!empty($input["coupon_atv_id"])) {
                $coupon_atv_model = new \app\massage\model\CouponAtv();
                $coupon_atv_model->invUser($user_id, $input["coupon_atv_id"]);
            }
            $qr_model = new \app\massage\model\ChannelQr();
            $qr_model->locationLogin($user_id);
            $register = 1;
            if (!empty($distribu_user)) {
                $insert["id"] = $user_id;
                $reseller_recommend_model = new \app\massage\model\ResellerRecommendCash();
                $reseller_recommend_model->addRecommendCash($insert, $distribu_user);
            }
        } else {
            $register = 0;
            $user_id = $user_info["id"];
            $user_model->dataUpdate(["id" => $user_id], $insert);
        }
        $user_info = $user_model->dataInfo(["id" => $user_id]);
        $key = "longbing_user_autograph_" . $user_info["openid"];
        $key = md5($key);
        setCache($key, $user_info, 259200, 666);
        $arr = ["data" => $user_info, "autograph" => $key, "is_register" => $register];
        $coach_model = new \app\massage\model\Coach();
        $cap_dis[] = ["user_id", "=", $user_info["id"]];
        $cap_dis[] = ["status", "in", [1, 2, 3, 4]];
        $cap_info = $coach_model->where($cap_dis)->field("status")->order("status")->find();
        $cap_info = !empty($cap_info) ? $cap_info->toArray() : [];
        $arr["coach_status"] = !empty($cap_info) ? $cap_info["status"] : -1;
        return $this->success($arr);
    }

    public function getLoginProtocol()
    {
        $input = $this->_param;
        $config = longbingGetAppConfig($this->uniacid);
        $data = !empty($config["login_protocol"]) ? $config["login_protocol"] : "";
        return $this->success($data);
    }

    public function getConfig()
    {
        $config = longbingGetAppConfig($this->uniacid);
        $data["login_protocol"] = $config["login_protocol"];
        $data["app_text"] = $config["app_text"];
        $data["primaryColor"] = $config["primaryColor"];
        $data["subColor"] = $config["subColor"];
        $data["app_logo"] = $config["app_logo"];
        $data["web_code_img"] = $config["web_code_img"];
        $data["information_protection"] = $config["information_protection"];
        $setting_model = new \app\massage\model\MassageConfig();
        $setting = $setting_model->dataInfo(["uniacid" => $this->uniacid]);
        $data["app_download_img"] = $setting["app_download_img"];
        $data["android_link"] = $setting["android_link"];
        $data["ios_link"] = $setting["ios_link"];
        $arr = getConfigSettingArr($this->uniacid, ["coach_android_link", "coach_ios_link"]);
        $data["coach_android_link"] = $arr["coach_android_link"];
        $data["coach_ios_link"] = $arr["coach_ios_link"];
        $short_config_model = new \app\massage\model\ShortCodeConfig();
        $short_config = $short_config_model->dataInfo(["uniacid" => $this->uniacid]);
        $data["short_code_status"] = $short_config["short_code_status"];
        return $this->success($data);
    }

    public function getWebConfig()
    {

        $input = $this->_param;
        $update = !empty($input["update"]) ? $input["update"] : 0;
        $config = longbingGetAppConfig($this->uniacid, false);
        $data["appid"] = $config["web_app_id"];
        $data["timestamp"] = time();
        $data["nonceStr"] = uniqid() . rand(10000, 99999);
//        echo 123;
        $wx_config = new \longbingcore\wxcore\WxSetting($this->uniacid);
        $jsapi_ticket = $wx_config->getWebTicket();
//        var_dump($jsapi_ticket);
//        $jsapi_ticket = "dsadsad";
        $url_now = $input["page"];
        $str = "jsapi_ticket=" . $jsapi_ticket . "&noncestr=" . $data["nonceStr"] . "&timestamp=" . $data["timestamp"] . "&url=" . $url_now;
        $signature = sha1($str);
        $data["signature"] = $signature;
        $data["jsapi_ticket"] = $jsapi_ticket;
        return $this->success($data);
    }

    public function checkToken()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = "2232eefrfg";
        $tmpArr = [$token, $timestamp, $nonce];
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if ($tmpStr == $signature) {
            echo $_GET["echostr"];
            exit;
        }
        return false;
    }

    public function incCoachOrderNum()
    {
        $time = rand(1, 3);
        \think\facade\Db::name("massage_service_coach_list")->where(["uniacid" => 666])->update(["order_num" => \think\facade\Db::raw("order_num+" . $time)]);
        $arr = [1 => rand(5, 10), 2 => rand(10, 20), 3 => rand(20, 30), 4 => rand(20, 30), 5 => rand(10, 20), 6 => rand(1, 5), 7 => rand(1, 3), 8 => rand(1, 3)];
        foreach ($arr as $key => $value) {
            \think\facade\Db::name("massage_service_service_list")->where(["id" => $key])->update(["sale" => \think\facade\Db::raw("sale+" . $value), "total_sale" => \think\facade\Db::raw("total_sale+" . $value)]);
        }
        return $this->success(true);
    }

    public function iosLogin()
    {
        $input = $this->_input;
        $uniacid = $this->uniacid;
        $input = $input["data"];
        $cap_id = !empty($input["cap_id"]) ? $input["cap_id"] : 0;
        $user_model = new \app\massage\model\User();
        $dis = ["openid" => $input["openId"], "status" => 1];
        $user_info = $user_model->dataInfo($dis);
        $familyName = !empty($input["fullName"]["familyName"]) ? $input["fullName"]["familyName"] : "";
        $giveName = !empty($input["fullName"]["giveName"]) ? $input["fullName"]["giveName"] : "";
        $name = $familyName . $giveName ? $familyName . $giveName : "默认用户";
        $insert = ["uniacid" => $uniacid, "nickName" => $name, "avatarUrl" => "https://lbqny.migugu.com/admin/farm/default-user.png", "openid" => $input["openId"], "push_id" => !empty($input["push_id"]) ? $input["push_id"] : "", "cap_id" => $cap_id, "last_login_type" => 4, "ios_openid" => $input["openId"]];
        $config = longbingGetAppConfig($this->uniacid, true);
        if (empty($user_info)) {
            if (!empty($input["pid"])) {
                if (getFxStatus($this->uniacid) == 1) {
                    $distribu_model = new \app\massage\model\DistributionList();
                    $dis = ["user_id" => $input["pid"], "status" => 2];
                    $distribu_user = $distribu_model->dataInfo($dis);
                    if (!empty($distribu_user)) {
                        $insert["pid"] = $input["pid"];
                    }
                } else {
                    $insert["pid"] = $input["pid"];
                }
            }
            $user_model->dataAdd($insert);
            $user_id = $user_model->getLastInsID();
            if (!empty($input["coupon_atv_id"])) {
                $coupon_atv_model = new \app\massage\model\CouponAtv();
                $coupon_atv_model->invUser($user_id, $input["coupon_atv_id"]);
            }
        } else {
            if (!($familyName . $giveName)) {
                unset($insert["nickName"]);
            }
            $user_id = $user_info["id"];
            $user_model->dataUpdate(["id" => $user_id], $insert);
        }
        $user_info = $user_model->dataInfo(["id" => $user_id]);
        $key = "longbing_user_autograph_" . $user_info["id"];
        $key = md5($key);
        setCache($key, $user_info, 259200, 0);
        $arr = ["data" => $user_info, "autograph" => $key];
        return $this->success($arr);
    }

    public function coachAccountLogin()
    {
        $input = $this->_input;
        $uniacid = $this->uniacid;
        $dis = ["uniacid" => $uniacid, "user_name" => $input["user_name"], "pass_word" => $input["pass_word"], "pass_word_text" => checkPass($input["pass_word"]), "status" => 1];
        $account_model = new \app\massage\model\CoachAccount();
        $find = $account_model->where($dis)->where("coach_id", ">", 0)->find();
        if (empty($find)) {
            return $this->error("账号不存在或密码错误", 200, 400);
        }
        $coach_model = new \app\massage\model\Coach();
        $where[] = ["id", "=", $find["coach_id"]];
        $where[] = ["status", "in", [1, 2, 3]];
        $coach_info = $coach_model->dataInfo($where);
        if (empty($coach_info)) {
            return $this->error("技师审核被驳回", 200, 400);
        }
        if (!empty($coach_info) && $coach_info["status"] == 1) {
            return $this->error("技师正在审核中", 200, 400);
        }
        $data = ["coach_id" => $coach_info["id"], "id" => $coach_info["user_id"], "uniacid" => $coach_info["uniacid"], "coach_account_login" => 1];
        $key = "longbing_coach_autograph_" . $coach_info["id"];
        $key = md5($key);
        setCache($key, $data, 259200, 0);
        $arr = ["data" => $data, "autograph" => $key];
        return $this->success($arr);
    }

    public function setCoachAccount()
    {
        $input = $this->_input;
        $account_model = new \app\massage\model\CoachAccount();
        $coach_account_phone_status = getConfigSetting($this->uniacid, "coach_account_phone_status");
        if ($coach_account_phone_status == 1) {
            if (empty($input["phone_code"])) {
                return $this->error("请输入验证码");
            }
            $phone = getConfigSetting($this->uniacid, "login_auth_phone");
            $phone = $input["user_name"];
            $key = $phone . "coachAccountSendShortMsgkey";
            if ($input["phone_code"] != getCache($key, $this->uniacid)) {
                return $this->error("验证码错误", 200, 400);
            }
        }
        $insert = ["uniacid" => $this->uniacid, "user_name" => $input["user_name"], "pass_word" => $input["pass_word"], "pass_word_text" => checkPass($input["pass_word"]), "status" => 1];
        $check = $account_model->where($insert)->find();
        if (!empty($check)) {
            if ($check["coach_id"] == 0) {
                return $this->error("账号密码失效", 200, 400);
            }
            return $this->error("该账号密码已被设置", 200, 400);
        }
        $res = $account_model->dataAdd($insert);
        $id = $account_model->getLastInsID();
        return $this->success($id);
    }

    public function bindCoachAccount()
    {
        $input = $this->_input;
        $account_model = new \app\massage\model\CoachAccount();
        $find = $account_model->where(["coach_id" => $input["coach_id"], "status" => 1])->delete();
        $res = $account_model->dataUpdate(["id" => $input["id"]], ["coach_id" => $input["coach_id"]]);
        return $this->success($res);
    }

    public function getCoachList()
    {
        $input = $this->_param;
        $account_model = new \app\massage\model\CoachAccount();
        $coach_model = new \app\massage\model\Coach();
        $coach_id = $account_model->where(["uniacid" => $this->uniacid, "status" => 1])->column("coach_id");
        $data = $coach_model->where(["uniacid" => $this->uniacid, "mobile" => $input["phone"]])->where("status", "in", [1, 2, 3])->where("id", "not in", $coach_id)->field("id as coach_id,coach_name,work_img")->order("id desc")->select()->toArray();
        return $this->success($data);
    }

    public function coachAccountSendShortMsg()
    {
        $input = $this->_input;
        $config = new \app\massage\model\ShortCodeConfig();
        $phone = getConfigSetting($this->uniacid, "login_auth_phone");
        $phone = $input["phone"];
        $key = "coachAccountSendShortMsgkey";
        $res = $config->sendSmsCode($phone, $this->uniacid, $key);
        if (!empty($res["Message"]) && $res["Message"] == "OK") {
            return $this->success(1);
        }
        return $this->error($res["Message"]);
    }
}

?>